package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    public final static String URL = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * C端用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public Result<UserLoginVO> login(UserLoginDTO dto) {
        //1.调用微信登录凭证校验接口
        //1.2封装数据
        Map<String,String> paraMap = new HashMap<>();
        paraMap.put("appid", weChatProperties.getAppid());
        paraMap.put("secret", weChatProperties.getSecret());
        paraMap.put("js_code", dto.getCode());
        paraMap.put("grant_type", "authorization_code");
        //1.1调用接口
        String body = HttpClientUtil.doGet(URL, paraMap);
        //1.3解析body字符串,获取openid
        Map map = JSON.parseObject(body, Map.class);
        String openid = (String) map.get("openid");
        //1.4判断opnid是否为空
        if (openid == null) {
            return Result.error(MessageConstant.LOGIN_FAILED);
        }
        //2.判断当前用户是否是新用户,如果是则注册
        //2.1根据openid查询user表
        User user = userMapper.getById(openid);
        //如果为空 则注册
        if (user==null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);

        }
        //3封装数据返回
        String token = JwtUtil.getToken(user.getId());

        UserLoginVO vo = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(openid)
                . build();

        return Result.success(vo);
    }
}
